import RequestBody from "./request-body.vue";
import Document from "./document/document.vue";
import InputTable from "./common/input-table.vue";

import { codemirror } from "vue-codemirror";
import "codemirror/addon/selection/active-line.js";
import "codemirror/addon/edit/closebrackets.js";
import "codemirror/mode/javascript/javascript";
import "codemirror/addon/lint/json-lint";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
import "codemirror/theme/base16-light.css";
import xhr from "./xhr";
import {nextTick}from 'vue'
import {selectOne,saveTestApi,selectPage} from "./api/apiReq";

const sessionKeyMap={
    one: "https-key-one",
    sydrKey:"sydrKey"
}
export default {
    components: { RequestBody, Document, InputTable, codemirror },
    mixins: [xhr],
    data() {
        return {
            sessionKey:'',
            forSaveModule:'',
            forSaveDesc:'',
            pageSize:5,
            curPage:0,
            totalPage:0,
             openTestApiDialog:false,
             saveTestApiDialog:false,
             ifFileExist:false,
 module:"",
 uriPath:"",
 fileList:[],
            httpProtocol: 'https',
            mainTab: 'form',
            url: {
                prefix: "",
                // main: "https://jsonplaceholder.typicode.com/posts",
                main: "",
            },
            httpMethod: "POST",

            cmOption: {
                tabSize: 4,
                styleActiveLine: true,
                lineNumbers: true,
                mode: "application/json",
                // theme: "monokai"
            },

            requestParams: {
                form: {
                    contentType: 'application/x-www-form-urlencoded',
                    data: [
                        {
                            enable: true,
                            key: "",
                            value: "",
                            desc: "",
                        },
                    ]
                },
                head: [
                    {
                        enable: false,
                        key: "mode",
                        value: "debug",
                        desc: "跳过token认证",
                    },
                    {
                        enable: false,
                        key: "sysid",
                        value: "",
                        desc: "系统ID",
                    },
                    {
                        enable: false,
                        key: "Source",
                        value: "",
                        desc: "来源端",
                    },
                    {
                        enable: false,
                        key: "Authorization",
                        value: "",
                        desc: "token",
                    },
                ],
                raw: {
                    contentType: 'application/json',
                    json: '',
                },
                queryString: [
                    {
                        enable: true,
                        key: "",
                        value: "",
                        desc: "",
                    },
                ],
            },
        
            requestAll: "",
            responseHead: "",
            responseBody: "",
        };
    },
    watch:{
        refArray:{
            handler: function (newVal,oldVal){
            // console.log(newVal)
        
            sessionStorage.setItem(sessionKeyMap[this.sessionKey], JSON.stringify(newVal));
            
        },
        deep: true
    }
    
        
    },  
    created() {
        const searchParams = new URLSearchParams(window.location.search)
        const key = searchParams.get('key')
        if(key&&key!='undefined'){
            this.sessionKey=key

        }else{
            this.sessionKey="sydrKey"
        }

      },
    computed:{
        upPageAble(){
            return (this.curPage<=1)?false:true;
           },
           downPageAble(){
            return (this.curPage<this.totalPage)?true:false;
           },
        refArray(){
            const{httpProtocol,url,httpMethod,mainTab}=this
            const reqHeaders=this.requestParams.head
            const reqQueryString=this.requestParams.queryString
            const formData=this.requestParams.form.data
            const formContentType=this.requestParams.form.contentType
            const rawJson=this.requestParams.raw.json
            const rawContentType=this.requestParams.raw.contentType




            return {
                httpProtocol,url,httpMethod,mainTab,reqHeaders,reqQueryString,formContentType,formData,rawJson,rawContentType
            }
        }
    },
    mounted() {
        this.handleConditionSelect();
        this.readDataFromSession();
    },
    methods: {
        async handleSaveStart(){
            if(!this.url.main || this.url.main.length==0){
                  alert("请填写请求url!");
                  return;
              }
              const one=await selectOne(this.url.main);
              if(one.id && one.id>0){
                this.ifFileExist=true;
                this.forSaveModule=one.module;
                this.forSaveDesc=one.des;
                  
              }else{
                this.ifFileExist=false;
                this.forSaveModule="";
                this.forSaveDesc=""
              }


            this.saveTestApiDialog=true;
        },
        readDataFromSession(){
            let key=sessionKeyMap[this.sessionKey];

            const cach= sessionStorage.getItem(key);
            if (cach) {
                const obj = JSON.parse(cach);
                const keys = Object.keys(obj);
                
                keys.forEach((key)=>{
                    nextTick(()=>{
                    
                        switch(key) {
                            case 'reqHeaders':
                              // 当expression的值等于value1时执行的代码块
                              
                              while (this.refArray.reqHeaders.length) {
                                this.refArray.reqHeaders.pop();
                              }
                              for(let i=0;i<obj[key].length;i++){
                                this.refArray.reqHeaders.push(obj[key][i])
                              }
                           
                            //   this.requestParams.head=obj[key]
                              break;
                            case 'reqQueryString':
                              // 当expression的值等于value2时执行的代码块
                              while (this.refArray.reqQueryString.length) {
                                this.refArray.reqQueryString.pop();
                              }
                              for(let i=0;i<obj[key].length;i++){
                                this.refArray.reqQueryString.push(obj[key][i])
                              }
    
                              break;
                            case 'formContentType':
    
                                // 当expression的值等于value2时执行的代码块
                                this.requestParams.form.contentType=obj[key]
    
                                break;
                            case 'formData':
                                    // 当expression的值等于value2时执行的代码块
                                    while (this.refArray.formData.length) {
                                        this.refArray.formData.pop();
                                      }
                                      for(let i=0;i<obj[key].length;i++){
                                        this.refArray.formData.push(obj[key][i])
                                      }
    
                                break;
                            case 'rawJson':
                                        // 当expression的值等于value2时执行的代码块
                                        this.requestParams.raw.json=obj[key]
                                break;
                            case 'rawContentType':
                                    // 当expression的值等于value2时执行的代码块
                                    this.requestParams.raw.contentType=obj[key]
                                break;
                
                            default:
                              // 当expression的值不匹配任何case时执行的代码块
                              this[key]=obj[key]
    
                          }
    
                });
            });
    
    
            }
        },
        async upPage(){
            if(this.curPage<=1){
                return;
         }
         let reqBody   = {
                 "module": this.module,
                 "uri":this.uriPath,
                 "pageNum": this.curPage-1,
                 "pageSize": this.pageSize
               }
            await this.dealPage(reqBody);
        },
         async downPage(){
            let reqBody   = {
                "module": this.module,
                "uri":this.uriPath,
                "pageNum": this.curPage+1,
                "pageSize": this.pageSize
              }
           await this.dealPage(reqBody);
        }
        ,
        async handleClick(row){
            sessionStorage.setItem(sessionKeyMap[this.sessionKey],row.content);
            this.readDataFromSession();
            this.openTestApiDialog=false;
        
        },
         openFiles(){
          this.openTestApiDialog=true;
        },
        async dealPage({module,uri,pageNum,pageSize}){
            const res= await selectPage({module,uri,pageNum,pageSize});
            this.fileList=res.records
            this.curPage=res.current;
            this.totalPage=res.pages;
        },
        async handleConditionSelect(){
                await this.dealPage({module:this.module,uri:this.uriPath,pageNum:1,pageSize:this.pageSize});
        },
        async handleSave(){
            if(this.forSaveModule==''){
                this.$message("功能模块不能为空");
                return;
            }
        
           let sessionData=sessionStorage.getItem(sessionKeyMap[this.sessionKey]);
           await saveTestApi({module:this.forSaveModule,
            des:this.forSaveDesc,
            uri:this.url.main,
            content:sessionData});
            this.$message("保存成功！");
            this.saveTestApiDialog=false;
        },
        load() {
            if(!this.url.main || this.url.main==''){
                alert("请填写请求url!");
                return;
            }

            let params, contentType;

            if ('form' === this.mainTab) {
                contentType = this.requestParams.form.contentType;
                params = json2fromParams(this.requestParams.form.data);
            } else if ('raw' === this.mainTab) {
                contentType = this.requestParams.raw.contentType;
                params = this.requestParams.raw.json;
            }
            let headers={};
            this.requestParams.head.filter((e)=>e.enable&&e.key&&e.key!='').forEach((e) =>{
                headers[e.key]=e.value} );
            let urlTemp=this.httpProtocol+"://"+this.url.main;
            let urlParams=this.requestParams.queryString.filter((e)=>e.enable&&e.key&&e.key!='')
            if(urlParams.length>0){
                urlTemp=urlTemp+"?"+json2fromParams(this.requestParams.queryString);
            }

            this.doRequest(this.httpMethod, urlTemp, params, {
                header: {
                    'content-type': contentType,
                    ...headers
                }
            });
        },
        authToken() {
            // 读取粘贴板
            try {
                navigator.clipboard.readText().then((v) => {
                    console.log("获取剪贴板成功：", v);
                    this.requestParams.head.unshift({
                        enable: true,
                        key: "Authorization",
                        value: "Bearer " + v,
                        desc: "认证用的 token",
                    });
                }).catch((v) => {
                    console.log("获取剪贴板失败: ", v);
                });
            } catch (e) {
                console.log(e);
                this.$Message.error('不支持读取粘贴板');
            }
        },

        formatJs() {
            let json = this.requestParams.raw.json;
            json = JSON.stringify(JSON.parse(json), null, 4);
            this.requestParams.raw.json = json;
        }
    },
};

function json2fromParams(arr) {
    let _arr = [];
    arr.filter((e)=>e.enable&&e.key&&e.key!='').forEach(({ key, value }) => _arr.push(key + '=' + encodeURIComponent(value)));
    return _arr.join('&');
}